import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/localStorage.js'

Vue.use(VueRouter)

  const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "about" */ '../views/layout/Home.vue'),

    children: [
      {
        path: 'role',
        name: 'Role',
        component: () => import(/* webpackChunkName: "about" */ '../views/role/Role.vue')
      },
      {
        path: 'user',
        name: 'User',
        component: () => import(/* webpackChunkName: "about" */ '../views/user/User.vue')
      }
    ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
    },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.path == "/login") {
    next();
  } else {
    if (getToken() != null) {
      next();
    } else {
      // router.push("/");
      router.push("/login");
    }
  }
});

/**
 * 重写路由的push方法
 */
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => {
    console.log("路由添加重复")
  })
}

export default router
